class MyBlockingQueue {
	/**
	 * 队列为满的时候，其他线程继续入队列就会进入阻塞状态，直到其他线程将元素出队列
	 * 队列为空的时候，其他线程继续出队列就会进入阻塞状态，直到其他线程将元素入队列
	 */
	private String  [] data=new String [1000];
	private volatile int head=0;
	private volatile int tail=0;
	private volatile int size=0;
	public void put(String str) throws InterruptedException {
		synchronized (this) {
			while(size==data.length) {
				//队列满了 之后，就会进入阻塞状态
				this.wait();
			}
			data[tail]=str;
			tail++;
			if(tail== data.length) {
				tail=0;
			}
			size++;
			this.notify();
		}
	}
	public String take() throws InterruptedException {
		//刚在这里的生产和消费者，使用wait的话，必须得加上锁
		synchronized (this) {
			while(size==0 ) {
				//队列为空就会进入到阻塞状态
				//直到put方法中notify将wait唤醒
				this.wait();
			}
			String ret=data[head];
			head++;
			if(head==data.length) {
				head=0;
			}
			size--;
			this.notify();
			return ret;
		}
	}
}
public class Demo17 {
	public static void main(String[] args) throws Exception{
		MyBlockingQueue queue=new MyBlockingQueue();
		Thread t2=new Thread(()->{
			while(true) {
				try {
					//改个
					String str=queue.take();
					System.out.println("消费者消费："+str);
					Thread.sleep(500);
				} catch (InterruptedException e) {
					throw new RuntimeException(e);
				}
			}
		});
		Thread t1=new Thread(()->{
			int num=1;
			while(true) {
				try {
					queue.put(num +"");
					System.out.println("生产者生产："+num);
					num++;
				} catch (InterruptedException e) {
					throw new RuntimeException(e);
				}
			}
		});
		t1.start();
		t2.start();
		System.out.println("程序开始");
	}
}
